<template>
  <div
    class="treeContainer"
    :id="'container' + (layerManagerShow ? '-1' : '-0')"
  >
    <!-- 显隐控制按钮 -->
    <div
      class="showController"
      :id="'controller' + (layerManagerShow ? '-1' : '-0')"
    >
      <div @click="layerManagerShowChange">
        <img
          src="@/assets/images/icon/infoList/返回.png"
          :style="{
            transform: layerManagerShow ? 'rotate(0deg)' : 'rotate(-180deg)',
          }"
        />
        <span v-show="!layerManagerShow">图层管理</span>
      </div>
    </div>
    <!-- 页面切换器 -->
    <div class="panel-title" v-show="layerManagerShow">
      <div class="tab">
        <div
          v-for="(data, index) in tabs"
          :key="index"
          :class="data.selected ? `selected` : `unselected`"
          @click="tabChange"
        >
          <img
            :src="require('@/assets/images/icon/标签页/' + data.img + '.png')"
          />
          <span>{{ data.text }}</span>
        </div>
      </div>
      <div class="bgBar"></div>
    </div>
    <!-- 图层管理 -->
    <transition name="fade1">
      <div class="collaspe" v-show="layerManagerShow && collapseShow">
        <el-collapse v-model="collapseRef">
          <el-collapse-item
            name="1"
            v-for="(data, index) in legendList"
            :key="index"
          >
            <template #title>
              | {{ data.label }}
              <info-filled />
            </template>
            <div class="smallLegend">
              <div>
                <span
                  >图例：
                  <span style="display: none">{{ data.label }}</span>
                </span>
                <img :src="data.picSrc" class="small" />
              </div>
            </div>
            <span style="margin-right: 10px">透明度:</span>
            <div class="opactiySlider">
              <el-slider v-model="data.opacity" @change="sliderChange(data)" />
            </div>
          </el-collapse-item>
          <div class="emptyLegend" v-show="emptyShow">
            <img src="@/assets/images/icon/标签页/空盒子.png" />
            <p>暂无图层</p>
          </div>
        </el-collapse>
      </div>
    </transition>
    <!-- 图层开关 -->
    <transition name="fade1">
      <div v-show="layerManagerShow && treeShow">
        <!-- 图层搜索框 -->
        <div class="layerSearcher">
          <el-input
            v-model="layerName"
            class="input-with-select"
            placeholder="请输入图层名"
            @keypress="handleKeyPress"
            disabled
          >
            <template #append>
              <el-button @click="layerSearch">
                <img
                  src="@/assets/images/icon/toolBar/框选查询.png"
                  alt="搜索"
                  style="width: 15px"
                />
              </el-button>
            </template>
          </el-input>
        </div>
        <div>
          <!-- 基础数据图层 -->
          <div class="tree" v-show="layerManagerShow">
            <el-tree
              :data="tree"
              ref="commonTreeRef"
              show-checkbox
              node-key="id"
              :default-expanded-keys="[-1]"
              @check-change="handleNodeCheckMain"
            />
          </div>
        </div>
      </div>
    </transition>
  </div>
</template> 

<script>
/* eslint-disable */
import { getCurrentInstance, onMounted, ref } from "vue";
import pubsub from "pubsub-js";
import axios from "axios";
import normalApi from "@/api/normalApi.js";

export default {
  name: "图层管理",
  data() {
    return {
      layerManagerShow: true,
      subList: [],
      treeShow: true,
      collapseShow: false,
      tabs: [
        {
          text: "图层管理",
          selected: false,
          img: "图层管理-未选",
          node: "collaspe",
        },
        {
          text: "图层选择",
          selected: true,
          img: "图层选择",
          node: "tree",
        },
      ],
      legendList: [],
      tree: [],
      emptyShow: true,
    };
  },
  setup() {
    const { proxy } = getCurrentInstance();
    const SampleData = require("@/store/mainTree.json");
    const commonTreeRef = ref(null);
    const layerName = ref("");
    let collapseRef = ["1"];

    onMounted(async () => {
      // 基础地图树型对象补id
      await addMapId();
      // 开启现状的图层
      openDefaultMap();
    });

    // 基础地图树型对象补id
    function addMapId() {
      let index = 0;
      // return normalApi.getMainTree().then((res) => {
      //   let SampleData = res.mainTree;
      //   SampleData.forEach((data) => {
      //     data.id = index.toString();
      //     index++;
      //   });
      //   proxy.tree = SampleData;
      //   // console.log(proxy.tree);
      // });
      SampleData.forEach((data) => {
        data.id = index.toString();
        index++;
      });
      proxy.tree = SampleData;
    }

    // 开启现状的图层
    function openDefaultMap() {
      let list = ["2024年4月无人机影像", "路网"];
      proxy.tree.forEach((data) => {
        list.forEach((element) => {
          if (element === data.label) {
            commonTreeRef.value.setChecked(data.id, true, true);
          }
        });
      });
    }

    //处理树形列表地图要素开关事件(基础地图)
    function handleNodeCheckMain(nodeData, isChecked, haveChild) {
      // 父节点免处理
      if (nodeData.id != -1) {
        // 发布
        pubsub.publish("basicalMapChange", { nodeData, isChecked });
        // 开启地图要素显示
        if (isChecked) {
          // 读取图例
          axios({
            method: "get",
            url: nodeData.url + "/legend",
          }).then((res) => {
            let picSrc = res.data.split('src="')[1].split('" alt')[0];
            proxy.legendList.push({
              picSrc,
              label: nodeData.label,
              opacity: 0,
            });
          });
        }
        // 关闭地图要素显示
        else {
          proxy.legendList.forEach((element) => {
            if (element.label === nodeData.label) {
              proxy.legendList.splice(proxy.legendList.indexOf(element), 1);
            }
          });
        }
      }
    }

    // 标签页切换
    function tabChange(event) {
      let node;
      if (event.target.nodeName === "IMG") {
        node = Array.from(event.target.parentNode.children)[1];
      } else if (event.target.nodeName === "SPAN") {
        node = event.target;
      } else {
        return;
      }
      let tabName = node.innerHTML;
      proxy.tabs.forEach((element) => {
        if (element.text === tabName) {
          if (element.selected) {
            return;
          } else {
            proxy.treeShow = !proxy.treeShow;
            proxy.collapseShow = !proxy.collapseShow;
            element.selected = true;
            element.img = element.text;
          }
        } else {
          element.selected = false;
          element.img = element.text + "-未选";
        }
      });
    }

    // 图层z坐标控制
    function layerIndexChange(event) {
      // 读取图层名
      let name = event.target.parentNode.firstChild.wholeText
        .split("| ")[1]
        .split(" ")[0];
      // 停止事件冒泡
      event.stopPropagation();
      // 次序交换
      for (let i = 0; i < proxy.legendList.length; i++) {
        if (proxy.legendList[i].text === name) {
          // 图层上移
          if (event.target.className === "titleIcon1") {
            if (i != 0) {
              let temp = proxy.legendList[i - 1];
              proxy.legendList[i - 1] = proxy.legendList[i];
              proxy.legendList[i] = temp;
              // 传输给地图
              pubsub.publish("layerIndexChange", {
                isUp: true,
                changedIndex: i,
              });
            }
          }
          // 图层下移
          else {
            if (i != proxy.legendList.length - 1) {
              let temp = proxy.legendList[i + 1];
              proxy.legendList[i + 1] = proxy.legendList[i];
              proxy.legendList[i] = temp;
              // 传输给地图
              pubsub.publish("layerIndexChange", {
                isUp: false,
                changedIndex: i,
              });
            }
          }
        }
      }
      // console.log(proxy.legendList);
    }

    // 图层透明度调整
    function sliderChange(data) {
      pubsub.publish("opacityChange", {
        label: data.label,
        opacity: data.opacity,
      });
    }

    // 图层名称查询
    function layerSearch() {
      // 读取输入值
      let name = layerName.value;
      proxy.tree.forEach((layer) => {
        if (layer.label.indexOf(name) != -1) {
          // 开启图层显示
          commonTreeRef.value.setChecked(layer.id, true, true);
        }
      });
    }

    // 控件显隐
    function layerManagerShowChange() {
      // 样式改变
      proxy.layerManagerShow = !proxy.layerManagerShow;
      // 信息传递
      pubsub.publish("layerManagerShowChange", proxy.layerManagerShow);
    }

    return {
      sliderChange,
      handleNodeCheckMain,
      commonTreeRef,
      layerName,
      tabChange,
      collapseRef,
      layerIndexChange,
      layerSearch,
      layerManagerShowChange,
    };
  },
  watch: {
    legendList: {
      handler(newValue) {
        this.emptyShow = !newValue.length > 0;
      },
      deep: true,
    },
  },
  beforeDestroy() {
    this.subList.forEach((element) => {
      pubsub.unsubscribe(element);
    });
  },
  beforeRouteLeave() {
    this.subList.forEach((element) => {
      pubsub.unsubscribe(element);
    });
  },
};
</script>

<style lang="less" scoped>
.showController {
  display: flex;
  align-items: center;
  position: absolute;
  right: 0%;
  z-index: 999999;
  padding: 5px;
  > div {
    background-color: #3f69e4;
    border-radius: 5px;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    flex-direction: column;
    > img {
      width: 20px;
      transition: transform 0.3s ease;
      transition: width 0.3s ease;
    }
    > span {
      text-align: center;
      font-weight: bold;
    }
  }
  > div:hover {
    cursor: pointer;
    > img {
      width: 23px;
    }
  }
}

#controller-1 {
  width: 20%;
  justify-content: right;
  height: 40px;
}

#controller-0 {
  width: 100%;
  justify-content: center;
  background-color: #3f69e4;
  height: 150px;
}

.treeContainer {
  position: absolute;
  top: 5.5%;
  // right: 0.25%;
  left: 0.25%;
  // float: right;
  height: 94%;
  background-color: white;
  z-index: 99999;
  border-radius: 5px;
  overflow: auto !important;
  transition: width 0.3s ease;
}

#container-1 {
  width: 15%;
}

#container-0 {
  width: 1.75%;
}

.panel-title {
  background-color: white;
  font-size: 120%;
  text-align: left;
  position: relative;
  > .bgBar {
    border-bottom: #e6e6e6 3px solid;
    float: left;
    position: absolute;
    top: 95%;
    width: 100%;
    background-color: #303133;
  }
  > .tab {
    position: relative;
    z-index: 9999;
    font-family: "黑体";
    display: flex;

    > .selected {
      display: inline-block;
      color: #3f69e4;
      padding: 2%;
      border-bottom: #3f69e4 3px solid;
      > img {
        width: 20px;
        margin-right: 1px;
      }
      > span {
        vertical-align: middle;
      }
    }
    > .unselected {
      display: inline-block;
      padding: 2%;
      color: #303133;
      > img {
        width: 20px;
        margin-right: 1px;
      }
      > span {
        vertical-align: middle;
      }
    }
  }
}

.emptyLegend {
  text-align: center;
  > img {
    margin-top: 10%;
    width: 20%;
  }
}

.opactiySlider {
  display: inline-block;
  width: 150px;
  margin-left: 15px;
}

.nodeLabel {
  font-size: 17px !important;
  font-weight: 500;
  color: #303133 !important;
}

.nodeIcon {
  width: 15px;
  margin-left: 2%;
}

.titleIcon1 {
  position: absolute;
  right: 14%;
  width: 20px;
}
.titleIcon2 {
  position: absolute;
  right: 8%;
  width: 20px;
}
.collaspe {
  position: absolute;
}
.layerSearcher {
  padding: 1.5%;
}
.tree {
  width: 96%;
  margin: 0% 2%;
}
.smallLegend {
  margin: 0 15px;
  display: inline-block;
  height: 30px;
  > div {
    position: relative;
    left: 5.5%;
    // top: 10px;
    height: 30px;
    > span {
      font-size: 110%;
    }
    > .small {
      min-height: 30px;
      min-width: 30px;
    }
  }
}
.bigLegend {
  > div {
    position: relative;
    left: 5.5%;
    > span {
      font-size: 120%;
    }
    > .big {
      display: block;
      width: 90%;
    }
  }
}
.fade1-enter-active {
  transition: all 0.3s;
}
.fade1-leave-active {
  transition: all 0.3s;
  transform: translateX(-100%);
}
.fade1-enter-from,
.fade1-leave-to {
  transition: 0.3s;
  transform: translateX(-100%);
}
.fade2-enter-active {
  transition: all 0.3s;
}
.fade2-leave-active {
  transition: all 0.3s;
  transform: translateX(-100%);
}
.fade2-enter-from,
.fade2-leave-to {
  transition: 0.3s;
  transform: translateX(-100%);
}
.el-tree {
  background: rgba(6, 19, 31, 0) !important;
}
.treeContainer::-webkit-scrollbar {
  width: 0px;
}
</style>